import mysql.connector

# 创建数据库连接类
class MySQLDatabase:
    # 初始化数据库连接
    def __init__(self, host, user, password, database):
        self.connection = mysql.connector.connect(
            host=host,
            user=user,
            password=password,
            database=database
        )
        self.cursor = self.connection.cursor()

    # 创建数据
    def create(self, query, data):
        self.cursor.execute(query, data)
        self.connection.commit()
        return self.cursor.lastrowid

    # 读取数据
    def read(self, query, data=None):
        if data:
            self.cursor.execute(query, data)
        else:
            self.cursor.execute(query)
        return self.cursor.fetchall()

    # 更新数据
    def update(self, query, data):
        self.cursor.execute(query, data)
        self.connection.commit()

    # 根据降序排列获取前三个数据
    def read_top_three(self, query):
        self.cursor.execute(query)
        return self.cursor.fetchall()[:3]
    # 根据条件查询记录条数，返回是否存在
    def check_exist(self, query, data):
        self.cursor.execute(query, data)
        return self.cursor.fetchone() is not None


    # 删除数据
    def delete(self, query, data):
        self.cursor.execute(query, data)
        self.connection.commit()


